<template>
  <div class="register-test">
    <div class="test-container">
      <el-card class="test-card">
        <template #header>
          <div class="card-header">
            <span>注册功能测试</span>
          </div>
        </template>

        <div class="test-content">
          <div class="test-section">
            <h3>快速注册测试</h3>
            <p>使用预设的测试数据快速注册一个新用户</p>
            
            <el-form
              ref="quickRegisterFormRef"
              :model="quickRegisterForm"
              :rules="quickRegisterRules"
              label-width="100px"
              class="quick-register-form"
            >
              <el-form-item label="用户名" prop="username">
                <el-input
                  v-model="quickRegisterForm.username"
                  placeholder="请输入用户名"
                  clearable
                />
              </el-form-item>

              <el-form-item label="邮箱" prop="email">
                <el-input
                  v-model="quickRegisterForm.email"
                  placeholder="请输入QQ邮箱"
                  clearable
                />
              </el-form-item>

              <el-form-item label="密码" prop="password">
                <el-input
                  v-model="quickRegisterForm.password"
                  :type="showPassword ? 'text' : 'password'"
                  placeholder="请输入密码"
                  show-password
                  clearable
                />
                <div class="password-hint">
                  密码必须包含字母、数字和特殊字符，且长度至少为8位
                </div>
              </el-form-item>

              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input
                  v-model="quickRegisterForm.confirmPassword"
                  :type="showConfirmPassword ? 'text' : 'password'"
                  placeholder="请确认密码"
                  show-password
                  clearable
                />
              </el-form-item>

              <el-form-item label="验证码" prop="verifyCode">
                <div class="verify-code-container">
                  <el-input
                    v-model="quickRegisterForm.verifyCode"
                    placeholder="请输入验证码"
                    style="width: 200px; margin-right: 10px;"
                  />
                  <el-button
                    @click="getVerifyCode"
                    :disabled="countdown > 0"
                    type="primary"
                  >
                    {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
                  </el-button>
                </div>
              </el-form-item>

              <el-form-item>
                <el-button
                  type="primary"
                  @click="handleQuickRegister"
                  :loading="registerLoading"
                  size="large"
                >
                  注册测试用户
                </el-button>
                <el-button @click="fillTestData" size="large">
                  填充测试数据
                </el-button>
                <el-button @click="clearForm" size="large">
                  清空表单
                </el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-divider />

          <div class="test-section">
            <h3>注册结果</h3>
            <div v-if="registerResult" class="result-display">
              <el-alert
                :title="registerResult.success ? '注册成功' : '注册失败'"
                :type="registerResult.success ? 'success' : 'error'"
                :description="registerResult.message"
                show-icon
                :closable="false"
              />
              <pre v-if="registerResult.data" class="json-display">{{ JSON.stringify(registerResult.data, null, 2) }}</pre>
            </div>
          </div>

          <el-divider />

          <div class="test-section">
            <h3>测试说明</h3>
            <ul class="test-instructions">
              <li>用户名：3-20个字符，建议使用英文和数字</li>
              <li>邮箱：必须是QQ邮箱格式，如：123456@qq.com</li>
              <li>密码：必须包含字母、数字和特殊字符，至少8位</li>
              <li>验证码：目前为测试环境，可以输入任意6位数字</li>
              <li>注册成功后会自动跳转到登录页面</li>
            </ul>
          </div>

          <div class="action-buttons">
            <el-button type="info" @click="goToLogin">
              前往登录页面
            </el-button>
            <el-button type="success" @click="goToRegister">
              前往完整注册页面
            </el-button>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { userRegister, sendRegisterCode } from '@/utils/apiService'

// 路由
const router = useRouter()

// 表单引用
const quickRegisterFormRef = ref(null)

// 状态
const registerLoading = ref(false)
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const countdown = ref(0)
const registerResult = ref(null)

// 表单数据
const quickRegisterForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  verifyCode: ''
})

// 表单验证规则
const quickRegisterRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3-20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入QQ邮箱', trigger: 'blur' },
    { pattern: /^[1-9]\d{4,10}@qq\.com$/, message: '请输入正确的QQ邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[\W_]).{8,}$/,
      message: '密码必须包含字母、数字和特殊字符，且长度至少为8位',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== quickRegisterForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  verifyCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码为6位数字', trigger: 'blur' }
  ]
})

// 方法
const fillTestData = () => {
  const timestamp = Date.now().toString().slice(-6)
  quickRegisterForm.username = `testuser${timestamp}`
  quickRegisterForm.email = `${timestamp}@qq.com`
  quickRegisterForm.password = 'Test123!@#'
  quickRegisterForm.confirmPassword = 'Test123!@#'
  quickRegisterForm.verifyCode = '123456'
  
  ElMessage.success('测试数据已填充')
}

const clearForm = () => {
  Object.keys(quickRegisterForm).forEach(key => {
    quickRegisterForm[key] = ''
  })
  registerResult.value = null
  ElMessage.info('表单已清空')
}

const getVerifyCode = async () => {
  if (!quickRegisterForm.email) {
    ElMessage.warning('请先输入邮箱')
    return
  }

  // 验证邮箱格式
  const emailRegex = /^[1-9]\d{4,10}@qq\.com$/
  if (!emailRegex.test(quickRegisterForm.email)) {
    ElMessage.warning('请输入正确的QQ邮箱格式')
    return
  }

  try {
    console.log(`发送验证码到: ${quickRegisterForm.email}`)

    // 调用发送验证码API
    const response = await sendRegisterCode(quickRegisterForm.email)

    console.log('🔍 验证码发送响应:', response)

    // 响应拦截器返回完整的response对象，实际数据在response.data中
    const responseData = response.data

    if (responseData.code === 200 || responseData.code === '200') {
      // 开始倒计时
      countdown.value = 60
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)

      ElMessage.success('验证码已发送，请查收邮箱')
    } else {
      console.log('❌ 验证码发送失败:', responseData)
      ElMessage.error(responseData.message || '验证码发送失败')
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error('验证码发送失败，请检查网络连接')
  }
}

const handleQuickRegister = async () => {
  if (!quickRegisterFormRef.value) return
  
  try {
    const valid = await quickRegisterFormRef.value.validate()
    if (!valid) {
      ElMessage.warning('请检查并完善注册信息')
      return
    }

    registerLoading.value = true
    registerResult.value = null

    // 准备注册数据
    const registerData = {
      username: quickRegisterForm.username,
      email: quickRegisterForm.email,
      password: quickRegisterForm.password,
      confirmPassword: quickRegisterForm.confirmPassword,
      verificationCode: quickRegisterForm.verifyCode
    }

    console.log('发送注册请求:', registerData)

    // 调用注册API
    const response = await userRegister(registerData)
    
    registerResult.value = {
      success: response.code === '200',
      message: response.message || (response.code === '200' ? '注册成功' : '注册失败'),
      data: response.data
    }
    
    if (response.code === '200') {
      ElMessage.success('注册成功！')
      
      // 3秒后跳转到登录页
      setTimeout(() => {
        router.push('/login')
      }, 3000)
    } else {
      ElMessage.error(response.message || '注册失败')
    }
  } catch (error) {
    console.error('注册错误:', error)
    
    registerResult.value = {
      success: false,
      message: error.message || '注册失败，请检查网络连接',
      data: null
    }
    
    ElMessage.error('注册失败，请检查网络连接或联系管理员')
  } finally {
    registerLoading.value = false
  }
}

const goToLogin = () => {
  router.push('/login')
}

const goToRegister = () => {
  router.push('/register')
}
</script>

<style scoped>
.register-test {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.test-container {
  max-width: 800px;
  margin: 0 auto;
}

.test-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 18px;
  color: #2c3e50;
}

.test-content {
  padding: 20px 0;
}

.test-section {
  margin-bottom: 30px;
}

.test-section h3 {
  margin-bottom: 15px;
  color: #409eff;
  font-size: 16px;
}

.quick-register-form {
  max-width: 500px;
}

.password-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.verify-code-container {
  display: flex;
  align-items: center;
}

.result-display {
  margin-top: 15px;
}

.json-display {
  background: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  margin-top: 10px;
  font-size: 12px;
  max-height: 200px;
  overflow-y: auto;
}

.test-instructions {
  color: #606266;
  line-height: 1.6;
}

.test-instructions li {
  margin-bottom: 8px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
  margin-top: 20px;
}
</style>
